package com.zeroinverse.fortunecookie;

import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.adwhirl.AdWhirlLayout.AdWhirlInterface;
import com.google.ads.AdRequest;
import com.google.ads.AdView;


public class FortuneCookieActivity extends Activity 
implements ImageButton.OnClickListener, AdWhirlInterface {

	private ImageButton cookieButton;
	private TextView messageTextView;
	private Boolean isPressedCookieButton;
	private Boolean isSaved;
	private String logTag = "FORTUNE_COOKIE";
	private ImageButton historyButton;
	private ImageButton shareButton;
	private ImageButton saveButton;
	private FortuneMessageDatabaseAdapter dbHelper = null;
	private Cursor cursor;
	private TextView touchMessageTextView;
	private SoundPool sound_pool;
	private int sound_click;
	private String selectedMessage;
	private int messageId;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		isPressedCookieButton = false;
		isSaved = false;

		/*
		AdWhirlManager.setConfigExpireTimeout(1000 * 60 * 5);
		//AdWhirlTargeting.setAge(20);
		AdWhirlTargeting.setTestMode(false);

		AdWhirlLayout adWhirlLayout = (AdWhirlLayout)findViewById(R.id.ad);
		adWhirlLayout.setAdWhirlInterface(this);
		*/
		AdView adView = (AdView)this.findViewById(R.id.ad);
		AdRequest request = new AdRequest();
		//request.setTesting(true);
	    adView.loadAd(request);

		cookieButton = (ImageButton)findViewById(R.id.cookie_button);
		cookieButton.setOnClickListener(this);

		historyButton = (ImageButton)findViewById(R.id.history_button);
		historyButton.setOnClickListener(this);

		shareButton = (ImageButton)findViewById(R.id.share_button);
		shareButton.setOnClickListener(this);

		saveButton = (ImageButton)findViewById(R.id.save_button);
		saveButton.setOnClickListener(this);


		//messageImageView = (ImageView)findViewById(R.id.message_imageview);
		messageTextView = (TextView)findViewById(R.id.message_textview);
		/*
        messageAnimation = AnimationUtils.loadAnimation(this, R.anim.message_anim);
        messageAnimation.setAnimationListener(this);
		 */

		touchMessageTextView = (TextView)findViewById(R.id.touch_message_textview);

		if (loadData() == false) {
			return;
		}
		/*
		if (dbHelper == null) {
			dbHelper = new FortuneMessageDatabaseAdapter(this);
			if (dbHelper == null) {
				Log.e(logTag, "Failed to init db helper");
				return;
			}
		}
		
		dbHelper.open();

		cursor = dbHelper.fetchAllMessages();
		if (cursor == null) {
			Log.e(logTag, "Failed to fetch all message");
			return;
		}
		startManagingCursor(cursor);
		*/

		sound_pool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0 );
		sound_click = sound_pool.load(this, R.raw.click, 1 );
	}
	
	public void onStop() {
		super.onStop();
		if (dbHelper != null) {
			dbHelper.close();
			dbHelper = null;
		}
	}
	
	public boolean loadData() {
		if (dbHelper == null) {
			dbHelper = new FortuneMessageDatabaseAdapter(this);
			if (dbHelper == null) {
				Log.e(logTag, "Failed to init db helper");
				return false;
			}
		}
		
		dbHelper.open();

		cursor = dbHelper.fetchAllMessages();
		if (cursor == null) {
			Log.e(logTag, "Failed to fetch all message");
			return false;
		}
		startManagingCursor(cursor);
		
		return true;
	}

	public void onClick(View v) {
		if ((ImageButton)v == cookieButton && isPressedCookieButton == false) {

			if (dbHelper == null) {
				if (loadData() == false) {
					return;
				}
			}
			
			int nr_row = cursor.getCount();
			if (nr_row == 0) {
				// No data - error
				Log.w(logTag, "No data in databases");
				return;
			}
			sound_pool.play(sound_click, 1f, 1f, 0, 0, 1f );

			int idx = new Random().nextInt(nr_row);
			cursor.moveToPosition(idx);
			selectedMessage = cursor.getString(
					cursor.getColumnIndex(dbHelper.getMessageTableKeyContent()));

			messageId = cursor.getInt(
					cursor.getColumnIndex(dbHelper.getMessageTableKeyId()));

			cursor.moveToFirst();
			isPressedCookieButton = true;
			isSaved = false;

			cookieButton.setBackgroundResource(R.drawable.background_after_click);
			messageTextView.setText(selectedMessage);
			messageTextView.setVisibility(TextView.VISIBLE);
			touchMessageTextView.setVisibility(TextView.INVISIBLE);

		} else if ((ImageButton)v == cookieButton && isPressedCookieButton == true) {
			cookieButton.setBackgroundResource(R.drawable.background);
			messageTextView.setVisibility(TextView.INVISIBLE);
			touchMessageTextView.setVisibility(TextView.VISIBLE);
			isPressedCookieButton = false;

		} else if ((ImageButton)v == historyButton) {
			Intent intent = new Intent(this, FortuneCookieHistoryListActivity.class);
			startActivity(intent);

		} else if ((ImageButton)v == shareButton && isPressedCookieButton == true) {
			Intent it = new Intent(android.content.Intent.ACTION_SEND);
			it.setType("text/plain");
			it.putExtra(Intent.EXTRA_SUBJECT, "Fortune Cookie");
			it.putExtra(Intent.EXTRA_TEXT, "Message of Fortune Cookie: " + selectedMessage);
			startActivity(Intent.createChooser(it, getResources().getString(R.string.send)));

		} else if ((ImageButton)v == saveButton && isPressedCookieButton == true && isSaved == false) {
			//Timestamp ts = new Timestamp((new java.util.Date()).getTime());
			if (dbHelper == null) {
				if (loadData() == false) {
					return;
				}
			}
			long t = (new java.util.Date()).getTime();
			if ((dbHelper.updateMessage(messageId, true, t)) == true) {
				// Success
				Toast.makeText(this, getResources().getString(R.string.save), Toast.LENGTH_SHORT).show();
				isSaved = true;
			} else {
			}
		}
	}

	public void adWhirlGeneric() {
		// TODO Auto-generated method stub

	}


}